package com.woniuxy.Mapper;

import com.woniuxy.entity.Appointments;
import com.woniuxy.vo.AppointmentsVo;
import org.apache.ibatis.annotations.*;

import java.math.BigDecimal;
import java.util.List;

@Mapper
public interface AppointmentMapper {
    @Insert("INSERT INTO appointments (" +
            "patient_name, patient_phone, schedule_id, app_status, " +
            "notes, id_card, date, time_solt,user_id,order_number" +
            ") VALUES (" +
            "#{patientName}, #{patientPhone}, #{scheduleId}, " +
            "#{appStatus, jdbcType=VARCHAR}, #{notes}, " +
            "#{idCard}, #{date}, #{timeSolt},#{userId},#{orderNumber}" +
            ")")
    @Options(useGeneratedKeys = true, keyProperty = "appointmentId")
    int buildAppointment(Appointments appointments);

    // 根据订单条件查询预约信息
    @Select("<script>" +
            "SELECT " +
            "a.appointment_id, " +
            "a.patient_name, " +
            "a.patient_phone, " +
            "a.date, " +
            "a.time_solt, " +
            "a.app_status, " +
            "a.id_card, " +
            "o.id as order_id, " +
            "o.order_number, " +
            "o.total_amount, " +
            "o.payment_amount, " +
            "o.payment_time, " +
            "o.create_time as order_create_time, " +
            "o.status as order_status, " +
            "o.payment_type " +
            "FROM appointments a " +
            "JOIN shop_orders o ON a.order_number = o.order_number " +  // 使用order_number连表
            "WHERE 1=1 " +
            "<if test='userId != null'>" +
            "   AND o.user_id = #{userId} " +
            "</if>" +
            "<if test='status != null'>" +
            "   AND o.status = #{status} " +
            "</if>" +
            "<if test='payType != null'>" +
            "   AND o.payment_type = #{payType} " +
            "</if>" +
            "ORDER BY o.create_time DESC" +
            "</script>")
    @Results({
            // 预约表字段映射
            @Result(property = "appointmentId", column = "appointment_id"),
            @Result(property = "patientName", column = "patient_name"),
            @Result(property = "patientPhone", column = "patient_phone"),
            @Result(property = "date", column = "date"),
            @Result(property = "timeSolt", column = "time_solt"),
            @Result(property = "appStatus", column = "app_status"),
            @Result(property = "idCard", column = "id_card"),

            // 订单表字段映射
            @Result(property = "orderNumber", column = "order_number"),
            @Result(property = "totalAmount", column = "total_amount"),
            @Result(property = "paymentAmount", column = "payment_amount"),
            @Result(property = "paymentType", column = "payment_type")
    })
    List<AppointmentsVo> selectByOrderConditions(
            @Param("userId") Integer userId,
            @Param("status") Integer status,
            @Param("payType") Integer payType);


    List<AppointmentsVo> selectByOrderCon(AppointmentsVo appointmentsVo);
    /**
     * 根据 userId、待确认状态、日期和时间段更新预约状态
     * @param userId 用户ID（条件）
     * @param timeSolt 时间段（条件）
     * @param date 日期（条件）
     * @param newAppStatus 新的预约状态（待更新值）
     * @return 受影响的行数（0：未找到符合条件数据，1：更新成功）
     */
    @Update("UPDATE appointments " +
            "SET app_status = #{newAppStatus} " +
            "WHERE user_id = #{userId} " +
            "  AND app_status = '待确认' " +
            "  AND time_solt = #{timeSolt} " +
            "  AND date = #{date}")
    int updateAppStatusByConditions(
            @Param("userId") Long userId,
            @Param("timeSolt") String timeSolt,
            @Param("date") String date,
            @Param("newAppStatus") String newAppStatus
    );
    @Update("UPDATE appointments " +
            "SET app_status = #{newAppStatus} " +
            "WHERE  order_number = #{oderNumber} ")
    int updateAppStatusByOderNumber(
            @Param("oderNumber") Long oderNumber,
            @Param("newAppStatus") String newAppStatus
    );
    /**
     * 根据用户ID、待支付状态、创建时间的日期和时间段更新订单状态为“已支付”（status=2）
     * @param order_number 订单创建日期（格式：yyyy-MM-dd，对应“date”条件）
     * @return 受影响的行数（0：未找到符合条件订单；1：更新成功）
     */
    @Update("UPDATE shop_orders " +
            "SET app_status = #{newStatus}, " +  // 更新状态为“2 已支付”
            "    update_time = CURRENT_TIMESTAMP " +  // 触发更新时间（若数据库未自动更新）
            "WHERE order_number = #{orderNumber} " )// 仅更新“待支付”状态订单
    int updateStatusToPaid(
            @Param("orderNumber") Long order_number,
            @Param("newStatus") Integer newStatus
    );
    /**
     * 根据排班ID更新可预约数（减1）和当前预约数（加1）
     * @param scheduleId 排班ID（主键，用于定位唯一排班记录）
     * @return 受影响的行数（0：未找到排班记录；1：更新成功）
     */
    @Update("UPDATE schedules " +
            "SET max_appointments = max_appointments - 1, " +
            "    current_appointments = current_appointments + 1 " +
            "WHERE schedule_id = #{scheduleId} " +
            "  AND max_appointments > 0 " +
            "  AND current_appointments < max_appointments") // 添加额外条件
    int updateAppointmentCounts(@Param("scheduleId") Long scheduleId);

    @Update("UPDATE schedules " +
            "SET max_appointments = max_appointments + 1, " +  // 注意字段间的逗号和空格
            "    current_appointments = current_appointments - 1 " +  // 此处添加空格！！！
            "WHERE schedule_id = #{scheduleId} " +
            "  AND max_appointments > 0")  // 避免max_appointments减为负数
    int increseAppointmentCounts(@Param("scheduleId") Long scheduleId);

    @Select("<script>" +
            "SELECT " +
            "a.appointment_id as appointmentId, " +
            "a.patient_name as patientName, " +
            "a.patient_phone as patientPhone, " +
            "a.schedule_id as scheduleId, " +
            "a.app_status as appStatus, " +
            "a.create_time as createTime, " +
            "a.notes, " +
            "a.id_card as idCard, " +
            "a.date, " +
            "a.time_solt as timeSolt, " +
            "a.user_id as userId, " +
            "o.total_amount as totalAmount, " +
            "o.payment_amount as paymentAmount, " +
            "o.pay_type as payType, " +
            "o.status, " +
            "o.order_number as orderNumber, " +
            "o.payment_type as paymentType, " +
            "s.time_slot as timeSolt, " +
            "d.name as doctorName " +
            "FROM appointments a " +
            "LEFT JOIN shop_orders o ON a.order_number = o.order_number " +
            "LEFT JOIN schedules s ON a.schedule_id = s.schedule_id " +
            "LEFT JOIN doctors d ON s.doctor_id = d.doctor_id " +
            "WHERE 1=1 " +
            "<if test='payType != null'> AND o.pay_type = #{payType} </if>" +
            "<if test='status != null'> AND o.status = #{status} </if>" +
            "<if test='userId != null'> AND a.user_id = #{userId} </if>" +
            "ORDER BY a.create_time DESC" +
            "</script>")
    List<AppointmentsVo> findAppointmentsByConditions(
            @Param("payType") String payType,
            @Param("status") Integer status,
            @Param("userId") Long userId);
}
